#include "downloadconfigmanager.h"
#include <QtXml/QDomDocument>
#include <QFile>
#include <QTextStream>

DownloadConfigManager::DownloadConfigManager(QObject *parent) :
    QObject(parent)
{
    m_file = NULL;
    m_ddom = NULL;
}

DownloadConfigManager::~DownloadConfigManager()
{
    delete m_file;
    delete m_ddom;
}

bool DownloadConfigManager::readConfig(const QString& type)
{
    delete m_file;
    delete m_ddom;
    m_file = new QFile( type );
    m_ddom = new QDomDocument;
    if( !m_file->open(QIODevice::ReadOnly | QIODevice::Text) )
        return false;
    if( !m_ddom->setContent(m_file) )
    {
        m_file->close();
        delete m_file;
        m_file = NULL;
        return false;
    }
    return true;
}

void DownloadConfigManager::writeXMLConfig()
{
    m_file = new QFile( COFIGPATH );
    m_ddom = new QDomDocument;
    if( !m_file->open(QFile::WriteOnly | QFile::Text) )
      return;

    ///////////////////////////////////////////////////////
    m_ddom->appendChild(
        m_ddom->createProcessingInstruction("xml","version='1.0' encoding='UTF-8'") );
    QDomElement downloader = m_ddom->createElement("QDownloader");
    m_ddom->appendChild(downloader);

    QSettings setting;
    QString bgThemeChoiced = setting.value("BGTHEMECHOICED").toString();
    QString bgTransparentChoiced = setting.value("BGTRANSPARENTCHOICED").toString();


    QDomElement bgTheme = m_ddom->createElement("bgTheme");
    bgTheme.setAttribute("value", bgThemeChoiced);
    downloader.appendChild(bgTheme);
    QDomElement backgroundSkin = m_ddom->createElement("bgTransparent");
    backgroundSkin.setAttribute("value", bgTransparentChoiced);
    downloader.appendChild(backgroundSkin);

    //Write to file
    QTextStream out(m_file);
    m_ddom->save(out,4);
}

QString DownloadConfigManager::readXmlByTagNameAndAttribute(const QString& tagName)
{
    QDomNodeList nodelist = m_ddom->elementsByTagName(tagName);
    return nodelist.at(0).toElement().attribute("value");
}

